import { defineStore } from 'pinia'
import { login, getInfo } from '../api/manager'
import { setToken, removeToken } from '@/composables/auth.js'

// 使用 defineStore 定义 store
export const useUserStore = defineStore('user', {
  state: () => ({
    // 用户信息
    user: {},
    // 侧边栏展开状态
    asideWidth: '250px',
    // 左侧菜单
    menus: [],
    ruleNames: [],
  }),
  actions: {
    // 记录用户信息
    SET_USERINFO(user) {
      this.user = user
    },
    // 展开收起侧边栏
    handleAsideWidth() {
      this.asideWidth = this.asideWidth == '250px' ? '64px' : '250px'
    },
    // 侧边栏菜单
    SET_MENUS(menus) {
      this.menus = menus
    },
    SET_RULE_NAMES(ruleNames) {
      this.ruleNames = ruleNames
    },
    // 获取用户信息
    async getinfo() {
      try {
        const res = await getInfo()
        this.SET_USERINFO(res)
        this.SET_MENUS(res.menus)
        this.SET_RULE_NAMES(res.ruleNames)
        return res
      } catch (error) {
        return Promise.reject(error)
      }
    },

    // 登录
    async login(formData) {
      try {
        const res = await login(formData)
        setToken(res.token)
        this.SET_USERINFO(res)
        return res
      } catch (error) {
        return Promise.reject(error)
      }
    },

    // 退出登录
    async logOut() {
      // 移除token
      removeToken()
      // 清除vuex用户状态
      this.SET_USERINFO({})
    },
  },
})
